<template>
  <div class="mall-container">
    <!-- 顶部购物车按钮 -->
    <div
      v-if="userStore.userInfo?.roleId === 3 || userStore.userInfo?.roleId === 4"
      class="cart-btn-container"
    >
      <el-badge :value="cartCount" :hidden="cartCount === 0" class="cart-badge">
        <el-button
          type="primary"
          :icon="ShoppingCart"
          @click="openCart"
          round
        >
          购物车
        </el-button>
      </el-badge>
    </div>

    <!-- 主体内容区 -->
    <div class="content-wrapper">
      <!-- 左侧分类菜单 -->
      <div class="category-menu">
        <div
          v-for="(category, index) in categories"
          :key="category.id ?? `category-${index}`"
          :class="['category-item', { active: activeCategory === category.id }]"
          @click="handleCategoryChange(category.id)"
        >
          <span class="category-icon"></span>
          <span class="category-name">{{ category.name }}</span>
        </div>
      </div>

      <!-- 右侧剧本列表 -->
      <div class="script-list-wrapper">
        <el-empty v-if="scriptList.length === 0 && !loading" description="暂无剧本" />

        <div v-else v-loading="loading" class="script-grid">
          <div
            v-for="script in scriptList"
            :key="script.id"
            class="script-card"
            @click="handleScriptClick(script)"
          >
            <div class="script-cover">
              <img
                :src="`${BASE_IMAGE_URL}/${script.contentFile}`"
                :alt="script.title"
                @error="handleImageError"
              />
            </div>
            <div class="script-info">
              <h3 class="script-title">{{ script.title }}</h3>
              <p class="script-author">{{ script.author }}</p>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="total > 0" class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[3, 5, 10, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- 剧本详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="剧本详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="script-detail">
        <div v-if="currentScript" class="detail-content">
          <!-- 剧本封面和基本信息 -->
          <div class="detail-header">
            <div class="detail-cover">
              <img
                :src="`${BASE_IMAGE_URL}/${currentScript.contentFile}`"
                :alt="currentScript.title"
                @error="handleImageError"
              />
            </div>
            <div class="detail-basic-info">
              <h2 class="detail-title">{{ currentScript.title }}</h2>
              <div class="info-item">
                <span class="info-label">作者：</span>
                <span class="info-value">{{ currentScript.author }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">出版社：</span>
                <span class="info-value">{{ currentScript.publishName }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">出版日期：</span>
                <span class="info-value">{{ currentScript.publishDate }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">分类：</span>
                <span class="info-value">{{ getCategoryName(currentScript.categoryId) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">已售：</span>
                <span class="info-value">{{ currentScript.sold }} 份</span>
              </div>
              <div class="info-item">
                <span class="info-label">使用天数：</span>
                <span class="info-value">{{ currentScript.usageDays }} 天</span>
              </div>
              <div class="info-item price-item">
                <span class="info-label">价格：</span>
                <span class="price-value">¥{{ currentScript.price }}</span>
              </div>
            </div>
          </div>

          <!-- 剧本简介 -->
          <div class="detail-description">
            <h3 class="section-title">剧本简介</h3>
            <p class="description-text">{{ currentScript.description || '暂无简介' }}</p>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button
          v-if="canBuy()"
          type="primary"
          @click="handleBuyClick"
        >
          加入购物车
        </el-button>
        <el-button
          v-else-if="userStore.userInfo?.roleId === 4"
          type="primary"
          @click="handleBuyClick"
        >
          注册成为店铺
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加剧本对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加剧本"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="剧本名称" prop="title">
          <el-input
            v-model="addForm.title"
            placeholder="请输入剧本名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input
            v-model="addForm.author"
            placeholder="请输入作者名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="出版社" prop="publishName">
          <el-input
            v-model="addForm.publishName"
            placeholder="请输入出版社名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker
            v-model="addForm.publishDate"
            type="date"
            placeholder="请选择出版日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="分类" prop="categoryId">
          <el-select
            v-model="addForm.categoryId"
            placeholder="请选择剧本分类"
            style="width: 100%"
          >
            <el-option
              v-for="category in categories.filter(c => c.id !== null)"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="addForm.price"
            :min="0"
            :precision="2"
            :step="1"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="使用天数" prop="usageDays">
          <el-input-number
            v-model="addForm.usageDays"
            :min="1"
            :step="1"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="剧本封面" prop="contentFile">
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            list-type="picture-card"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议上传5:7比例的图片</div>
        </el-form-item>

        <el-form-item label="剧本简介" prop="description">
          <el-input
            v-model="addForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入剧本简介"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleCancelAdd">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmitAdd">
          提交
        </el-button>
      </template>
    </el-dialog>

    <!-- 购物车对话框 -->
    <el-dialog
      v-model="cartVisible"
      title="我的购物车"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="cart-container">
        <el-empty v-if="cartList.length === 0 && !cartLoading" description="购物车是空的" />

        <div v-else v-loading="cartLoading">
          <!-- 购物车列表 -->
          <el-table :data="cartList" border style="width: 100%">
            <el-table-column label="封面" width="100">
              <template #default="{ row }">
                <el-image
                  :src="`${BASE_IMAGE_URL}/${row.scriptVO?.contentFile}`"
                  fit="cover"
                  style="width: 60px; height: 84px; border-radius: 4px"
                >
                  <template #error>
                    <div class="image-error-small">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </template>
            </el-table-column>

            <el-table-column prop="scriptVO.title" label="剧本名称" min-width="150" >
            </el-table-column>

            <el-table-column prop="scriptVO.author" label="作者" width="120" />

            <el-table-column prop="scriptVO.publisherName" label="出版社" width="150" />

            <el-table-column prop="scriptVO.categoryId" label="分类" width="100">
              <template #default="{ row }">
                {{ getCategoryName(row.scriptVO?.categoryId) }}
              </template>
            </el-table-column>

            <el-table-column prop="script.price" label="价格" width="100">
              <template #default="{ row }">
                <span class="price-text">¥{{ row.scriptVO?.price }}</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button
                  link
                  type="danger"
                  :icon="Delete"
                  @click="handleDeleteCartItem(row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 购物车总计 -->
          <div class="cart-summary">
            <div class="summary-item">
              <span class="summary-label">共计：</span>
              <span class="summary-value">{{ cartList.length }} 个剧本</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">总价：</span>
              <span class="summary-price">¥{{ cartTotalPrice() }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="cart-footer">
          <el-button @click="handleClearCart" :disabled="cartList.length === 0">
            清空购物车
          </el-button>
          <div>
            <el-button @click="cartVisible = false">关闭</el-button>
            <el-button
              type="primary"
              @click="handleCheckout"
              :disabled="cartList.length === 0"
            >
              结算 (¥{{ cartTotalPrice() }})
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getScriptListAPI, getScriptListByCategoryIdAPI, uploadScriptImageAPI, addScriptAPI } from '@/api/mall'
import { getShopByUserIdAPI } from '@/api/shop'
import { addCartAPI, getCartListAPI, deleteCartItemAPI, clearCartAPI, checkoutCartAPI } from '@/api/script'
import { onMounted, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import type { Script } from '@/types/script'
import { useUserStore } from '@/stores/modules/user'
import { Plus, ShoppingCart, Delete, Picture } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadUserFile, UploadFile } from 'element-plus'

const BASE_IMAGE_URL = import.meta.env.VITE_API_BASE_URL
// 用户store
const userStore = useUserStore()
const router = useRouter()

// 响应式数据
const scriptList = ref<Script[]>([])
const loading = ref(false)
const activeCategory = ref<number | null>(null)
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 店铺信息
const shopInfo = ref<{ id: number } | null>(null)

// 购物车项类型
interface CartItem {
  id: number
  script?: Script
}

// 购物车相关
const cartVisible = ref(false)
const cartList = ref<CartItem[]>([])
const cartLoading = ref(false)
const cartCount = ref(0)

// 详情对话框相关
const detailVisible = ref(false)
const currentScript = ref<Script | null>(null)

// 添加剧本对话框相关
const addDialogVisible = ref(false)
const submitLoading = ref(false)
const addFormRef = ref<FormInstance>()
const fileList = ref<UploadUserFile[]>([])
const uploadedFile = ref<File | null>(null)

// 添加剧本表单
const addForm = reactive({
  title: '',
  author: '',
  publishName: '',
  publishDate: '',
  categoryId: null as number | null,
  price: 0,
  usageDays: 7,
  contentFile: '',
  description: '',
  status: 0,
  sold: 0,
  publisherId: 0,
  shopId: 0
})

// 表单验证规则
const addFormRules: FormRules = {
  title: [
    { required: true, message: '请输入剧本名称', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者名称', trigger: 'blur' }
  ],
  publishName: [
    { required: true, message: '请输入出版社名称', trigger: 'blur' }
  ],
  publishDate: [
    { required: true, message: '请选择出版日期', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择剧本分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  usageDays: [
    { required: true, message: '请输入使用天数', trigger: 'blur' }
  ],
  contentFile: [
    { required: true, message: '请上传剧本封面', trigger: 'change' }
  ]
}

// 分类列表
const categories = [
  { id: null, name: '全部' },
  { id: 1, name: '剧情类' },
  { id: 2, name: '喜剧类' },
  { id: 3, name: '悬疑类' },
  { id: 4, name: '历史类' },
  { id: 5, name: '科幻类' }
]

// 获取剧本列表
const getScriptList = async () => {
  loading.value = true
  try {
    let res
    // 根据是否选择分类调用不同的接口
    if (activeCategory.value === null) {
      // 获取全部剧本
      const response = await getScriptListAPI({
        page: currentPage.value,
        size: pageSize.value
      })
      res = response.data
    } else {
      // 根据分类ID获取剧本
      const response = await getScriptListByCategoryIdAPI({
        categoryId: activeCategory.value,
        page: currentPage.value,
        size: pageSize.value
      })
      res = response.data
    }

    if (res.code !== 1) {
      ElMessage.error(res.msg || '获取剧本列表失败')
      return
    }

    scriptList.value = res.data.records || []
    total.value = res.data.total || 0
  } catch {
    ElMessage.error('网络请求失败')
  } finally {
    loading.value = false
  }
}

// 分类切换
const handleCategoryChange = (categoryId: number | null) => {
  activeCategory.value = categoryId
  currentPage.value = 1
  getScriptList()
}

// 页码改变
const handlePageChange = (page: number) => {
  currentPage.value = page
  getScriptList()
}

// 每页数量改变
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  getScriptList()
}

// 点击剧本卡片
const handleScriptClick = (script: Script) => {
  currentScript.value = script
  detailVisible.value = true
}

// 获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = categories.find(cat => cat.id === categoryId)
  return category?.name || '未知分类'
}

// 图片加载失败处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement
  target.src = 'https://lvyou-1332935562.cos.ap-nanjing.myqcloud.com/ceshi/IMG_1351.PNG'
}

// 获取店铺信息
const getShopInfo = async () => {
  // 只有店铺角色才需要获取店铺信息
  if (userStore.userInfo?.roleId !== 3) {
    return
  }

  try {
    const { data: res } = await getShopByUserIdAPI()
    if (res.code === 1 && res.data !== null) {
      shopInfo.value = res.data
    } else {
      shopInfo.value = null
    }
  } catch (error) {
    console.error('获取店铺信息失败:', error)
    shopInfo.value = null
  }
}

// 检查是否可以购买
const canBuy = () => {
  const roleId = userStore.userInfo?.roleId

  // 游客（roleId: 4）不能购买
  if (roleId === 4) {
    return false
  }

  // 店铺（roleId: 3）必须有 shopId 才能购买
  if (roleId === 3) {
    return shopInfo.value?.id != null
  }

  return false
}

// 处理加入购物车点击
const handleBuyClick = () => {
  const roleId = userStore.userInfo?.roleId

  // 游客点击跳转到注册页面
  if (roleId === 4) {
    ElMessageBox.confirm(
      '您需要注册成为店铺才能购买剧本，是否前往注册？',
      '提示',
      {
        confirmButtonText: '前往注册',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      router.push({ path: '/register', query: { role: 'shop' } })
    }).catch(() => {
      // 取消操作
    })
    return
  }

  // 店铺用户加入购物车
  if (roleId === 3 && shopInfo.value?.id) {
    handleAddToCart()
  }
}

// 加入购物车
const handleAddToCart = async () => {
  if (!shopInfo.value?.id) {
    ElMessage.error('店铺信息异常，无法加入购物车')
    return
  }

  if (!currentScript.value?.id) {
    ElMessage.error('剧本信息异常，无法加入购物车')
    return
  }

  try {
    const res = await addCartAPI(shopInfo.value.id, currentScript.value.id)
    if (res.data.code === 1) {
      ElMessage.success('已加入购物车！')
      // 更新购物车数量
      getCartCount()
    } else {
      ElMessage.error(res.data.msg || '加入购物车失败')
    }
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败，请稍后重试')
  }
}

// 获取购物车列表
const getCartList = async () => {
  if (!shopInfo.value?.id) {
    return
  }

  cartLoading.value = true
  try {
    const res = await getCartListAPI(shopInfo.value.id)
    console.log('res',res);

    if (res.data.code === 1) {
      cartList.value = res.data.data || []
      console.log('carList',cartList.value);

      cartCount.value = cartList.value.length
    } else {
      ElMessage.error(res.data.msg || '获取购物车失败')
    }
  } catch (error) {
    console.error('获取购物车失败:', error)
    ElMessage.error('获取购物车失败')
  } finally {
    cartLoading.value = false
  }
}

// 获取购物车数量
const getCartCount = async () => {
  if (!shopInfo.value?.id) {
    return
  }

  try {
    const res = await getCartListAPI(shopInfo.value.id)
    if (res.data.code === 1) {
      cartCount.value = res.data.data?.length || 0
    }
  } catch (error) {
    console.error('获取购物车数量失败:', error)
  }
}

// 打开购物车
const openCart = () => {
  const roleId = userStore.userInfo?.roleId

  // 游客点击跳转到注册页面
  if (roleId === 4) {
    ElMessageBox.confirm(
      '您需要注册成为店铺才能使用购物车，是否前往注册？',
      '提示',
      {
        confirmButtonText: '前往注册',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      router.push({ path: '/register', query: { role: 'shop' } })
    }).catch(() => {
      // 取消操作
    })
    return
  }

  if (!shopInfo.value?.id) {
    ElMessage.warning('请先完成店铺资质审核')
    return
  }

  cartVisible.value = true
  getCartList()
}

// 删除购物车项
const handleDeleteCartItem = async (id: number) => {
  try {
    const res = await deleteCartItemAPI(id)
    if (res.data.code === 1) {
      ElMessage.success('删除成功')
      getCartList()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 清空购物车
const handleClearCart = () => {
  if (cartList.value.length === 0) {
    ElMessage.warning('购物车已经是空的')
    return
  }

  ElMessageBox.confirm(
    '确定要清空购物车吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    if (!shopInfo.value?.id) return

    try {
      const res = await clearCartAPI(shopInfo.value.id)
      if (res.data.code === 1) {
        ElMessage.success('购物车已清空')
        getCartList()
      } else {
        ElMessage.error(res.data.msg || '清空失败')
      }
    } catch (error) {
      console.error('清空购物车失败:', error)
      ElMessage.error('清空失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 结算购物车
const handleCheckout = () => {
  if (cartList.value.length === 0) {
    ElMessage.warning('购物车是空的，无法结算')
    return
  }

  ElMessageBox.confirm(
    `确定要结算购物车中的 ${cartList.value.length} 个剧本吗？`,
    '确认结算',
    {
      confirmButtonText: '确定结算',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    if (!shopInfo.value?.id) return

    try {
      const res = await checkoutCartAPI(shopInfo.value.id)
      if (res.data.code === 1) {
        ElMessage.success('结算成功！')
        cartVisible.value = false
        getCartList()
        // 刷新剧本列表
        getScriptList()
      } else {
        ElMessage.error(res.data.msg || '结算失败')
      }
    } catch (error) {
      console.error('结算失败:', error)
      ElMessage.error('结算失败，请稍后重试')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 计算购物车总价
const cartTotalPrice = () => {
  console.log('cartList.value',cartList.value);
  return cartList.value.reduce((total, item) => {

    return total + (item.scriptVO.price || 0)
  }, 0).toFixed(2)
}


// 文件选择处理
const handleFileChange = (file: UploadFile) => {
  uploadedFile.value = file.raw as File
  addForm.contentFile = 'pending'
  // 手动触发表单验证
  addFormRef.value?.validateField('contentFile')
}

// 文件移除处理
const handleFileRemove = () => {
  uploadedFile.value = null
  addForm.contentFile = ''
  addFormRef.value?.validateField('contentFile')
}

// 重置表单
const resetAddForm = () => {
  addFormRef.value?.resetFields()
  fileList.value = []
  uploadedFile.value = null
  Object.assign(addForm, {
    title: '',
    author: '',
    publishName: '',
    publishDate: '',
    categoryId: null,
    price: 0,
    usageDays: 7,
    contentFile: '',
    description: '',
    status: 0,
    sold: 0,
    publisherId: 0,
    shopId: 0
  })
}

// 取消添加
const handleCancelAdd = () => {
  addDialogVisible.value = false
  resetAddForm()
}

// 提交添加剧本
const handleSubmitAdd = async () => {
  if (!addFormRef.value) return

  try {
    // 验证表单
    await addFormRef.value.validate()

    submitLoading.value = true

    // 先上传图片
    if (!uploadedFile.value) {
      ElMessage.error('请上传剧本封面')
      submitLoading.value = false
      return
    }

    // 上传图片
    console.log('uploadedFile.value',uploadedFile.value)
    const publisherId = (userStore.userInfo as { id: number }).id || 0
    const uploadRes = await uploadScriptImageAPI(uploadedFile.value, publisherId)
    console.log('uploadRes',uploadRes)
    if (uploadRes.data.code !== 1) {
      ElMessage.error(uploadRes.data.msg || '图片上传失败')
      submitLoading.value = false
      return
    }

    // 获取图片URL
    const imageUrl = uploadRes.data.data

    // 准备提交数据
    const submitData = {
      ...addForm,
      contentFile: imageUrl,
      status: 0,
      sold: 0,
      publisherId: publisherId,
      shopId: 0,
    }

    // 提交剧本
    console.log('submitData',submitData)
    const res = await addScriptAPI(submitData as Script)
    if (res.data.code !== 1) {
      ElMessage.error(res.data.msg || '添加剧本失败')
      return
    }

    ElMessage.success('添加剧本成功')
    addDialogVisible.value = false
    resetAddForm()

    // 刷新列表
    currentPage.value = 1
    getScriptList()
  } catch (error) {
    console.error('添加剧本失败:', error)
    if (error !== false) { // 排除表单验证失败
      ElMessage.error('添加剧本失败')
    }
  } finally {
    submitLoading.value = false
  }
}

onMounted(async () => {
  getScriptList()
  await getShopInfo()
  // 获取购物车数量
  if (userStore.userInfo?.roleId === 3 && shopInfo.value?.id) {
    getCartCount()
  }
})
</script>

<style scoped>
.mall-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
  position: relative;
}

/* 购物车按钮容器 */
.cart-btn-container {
  position: fixed;
  top: 80px;
  right: 30px;
  z-index: 999;
}

.cart-badge {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  border-radius: 20px;
}

/* 主体内容 */
.content-wrapper {
  display: flex;
  gap: 20px;
}

/* 左侧分类菜单 */
.category-menu {
  width: 150px;
  background: #fff;
  border-radius: 4px;
  padding: 8px 0;
  height: fit-content;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  color: #606266;
}

.category-item:hover {
  background-color: #f5f7fa;
}

.category-item.active {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: 500;
}

.category-icon {
  width: 8px;
  height: 8px;
  background: currentColor;
  border-radius: 50%;
}

/* 右侧剧本列表 */
.script-list-wrapper {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  padding: 24px;
  min-height: 600px;
}

.script-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.script-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.script-card:hover {
  transform: translateY(-4px);
}

.script-cover {
  width: 100%;
  aspect-ratio: 5 / 7;
  overflow: hidden;
  border-radius: 4px;
  background: #f5f5f5;
  margin-bottom: 12px;
}

.script-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.script-info {
  text-align: left;
}

.script-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 6px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.script-author {
  font-size: 12px;
  color: #909399;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .script-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .content-wrapper {
    flex-direction: column;
  }

  .category-menu {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    padding: 12px;
  }

  .category-item {
    padding: 8px 16px;
  }

  .script-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 16px;
  }
}

/* 剧本详情样式 */
.script-detail {
  min-height: 400px;
}

.detail-content {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
}

.detail-cover {
  width: 200px;
  flex-shrink: 0;
}

.detail-cover img {
  width: 100%;
  height: 280px;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.detail-basic-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
  line-height: 1.4;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1.6;
}

.info-label {
  color: #909399;
  min-width: 80px;
}

.info-value {
  color: #606266;
  flex: 1;
}

.price-item {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.price-value {
  font-size: 28px;
  font-weight: 600;
  color: #f56c6c;
}

.detail-description {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.description-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}

/* 详情对话框响应式 */
@media (max-width: 768px) {
  .detail-header {
    flex-direction: column;
    align-items: center;
  }

  .detail-cover {
    width: 160px;
  }

  .detail-cover img {
    height: 224px;
  }

  .detail-title {
    font-size: 20px;
  }

  .price-value {
    font-size: 24px;
  }
}

/* 上传组件样式 */
.upload-demo {
  display: flex;
  justify-content: flex-start;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 购物车容器 */
.cart-container {
  min-height: 300px;
}

.image-error-small {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 84px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.price-text {
  color: #f56c6c;
  font-weight: 600;
  font-size: 14px;
}

/* 购物车总计 */
.cart-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 40px;
  margin-top: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.summary-label {
  font-size: 14px;
  color: #606266;
}

.summary-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.summary-price {
  font-size: 24px;
  color: #f56c6c;
  font-weight: 600;
}

/* 购物车底部 */
.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.cart-footer > div {
  display: flex;
  gap: 10px;
}

/* 响应式 - 购物车按钮 */
@media (max-width: 768px) {
  .cart-btn-container {
    top: 70px;
    right: 20px;
  }
}
</style>
